package com.kim.interceptor;

import com.kim.pojo.Result;
import com.kim.utils.JwtUtil;
import com.kim.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{
        //令牌验证
        String token = request.getHeader("Authorization");

        //验证token
        try {
            //从redis中获取相同的token
            String redistoken = stringRedisTemplate.opsForValue().get(token);
            if (redistoken == null){
                //token已经失效了
                throw new RuntimeException();  //运行时异常，被catch捕获到，返回false
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //将ThreadLocal清除，为了防止内存泄露
        ThreadLocalUtil.remove();
    }
}
